package cn.felord.security.autoconfigure.captcha;

import cn.felord.security.autoconfigure.AbstractLoginChannelProcessor;
import cn.felord.security.autoconfigure.ChannelUserDetailsService;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationProvider;

import javax.servlet.http.HttpServletRequest;

/**
 * @author n1
 * @since 2021/6/29 9:45
 */
public class CaptchaLoginChannelProcessor extends AbstractLoginChannelProcessor<CaptchaAuthenticationToken> {

    private static final String CHANNEL_ID = "captcha";
    /**
     * The constant SPRING_SECURITY_FORM_PHONE_KEY.
     */
    private static final String SPRING_SECURITY_FORM_PHONE_KEY = "phone";
    /**
     * The constant SPRING_SECURITY_FORM_CAPTCHA_KEY.
     */
    private static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "captcha";


    public CaptchaLoginChannelProcessor(ChannelUserDetailsService channelUserDetailsService, CaptchaService captchaService) {
        super(CHANNEL_ID, new CaptchaAuthenticationProvider(channelUserDetailsService, captchaService));
    }

    public CaptchaLoginChannelProcessor(String channel, AuthenticationProvider appAuthenticationProvider) {
        super(channel, appAuthenticationProvider);
    }

    @Override
    public CaptchaAuthenticationToken doAuthenticationRequest(HttpServletRequest request) {
        String phone = obtainPhone(request);
        String captcha = obtainCaptcha(request);

        if (phone == null) {
            phone = "";
        }

        if (captcha == null) {
            captcha = "";
        }

        phone = phone.trim();
        captcha = captcha.trim();

        return new CaptchaAuthenticationToken(
                phone, captcha);
    }

    /**
     * Obtain captcha string.
     *
     * @param request the request
     * @return the string
     */
    @Nullable
    protected String obtainCaptcha(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_CAPTCHA_KEY);
    }

    /**
     * Obtain phone string.
     *
     * @param request the request
     * @return the string
     */
    @Nullable
    protected String obtainPhone(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_PHONE_KEY);
    }
}
